<template>
  <div class="bar-warper">
    <div class="title">{{ title }}</div>
    <div class="unit">{{ unit }}</div>
    <div :id="id" class="box-bar"></div>
  </div>
</template>
<script>
import { Chart } from '@antv/g2';
export default {
  props: {
    title: {
      type: String,
    },
    unit: {
      type: String,
    },
    id: {
      type: String,
    },
    color: {
      type: String,
      default: "#32f9fd",
    },
    datas: {
      type: Array,
    },
  },
  data: {
    chart: {},
  },
  watch: {
    datas() {
      if ( this.chart) {
      this.chart.changeData(this.datas) 
        
      }
    },
  },
  mounted() {
    setTimeout(() => {
      const data = this.datas;
      const chart = new Chart({
        container: this.id,
        autoFit: true,
        animate: true,
        padding: [30, 50, 30, 50],
      });
      this.chart = chart;
      chart.data(data);

      chart.axis("type", {
        tickLine: false,
        grid: null,
      });
      chart.axis("value", {
        grid: null,
        tickLine: false,
        label: {
          formatter: (val) => {
            if (val < 1 && val > 0) {
              return val * 100 + "%";
            } else {
              return val;
            }
          },
        },
      });

      chart.tooltip({
        showMarkers: false,
      });
      chart.interval().position("type*value").color(this.color);
      chart.interaction("element-active");

      chart.render();
    }, 1000);
  },
};
</script>
<style lang="less" scoped>
.box-bar {
  height: 100%;
  width: 100%;
}
.bar-warper {
  position: relative;
  height: 100%;
  width: 100%;
}
.title {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  text-align: center;
  font-size: 14px;
  color: #fff;
}
.unit {
  position: absolute;
  top: 0;
  left: 10px;
  width: 70px;
  text-align: center;
  font-size: 14px;
  color: #8c8c8c;
}
</style>